from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import nmap

app = FastAPI()
origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class ScanRequest(BaseModel):
    ipAddress: str

@app.post("/scan")
async def scan_ports(scan_request: ScanRequest):
    nm = nmap.PortScanner()
    results = nm.scan(scan_request.ipAddress, arguments="-sV -p 1-65535")
    host_up = results["nmap"]["scanstats"]["uphosts"]
    if host_up == "0":
        raise HTTPException(status_code=404, detail="Host is down")
    if not results["scan"]:
        raise HTTPException(status_code=404, detail="No results found")
    open_ports = []
    for port in results["scan"][scan_request.ipAddress]["tcp"]:
        if results["scan"][scan_request.ipAddress]["tcp"][port]["state"] == "open":
            service = results["scan"][scan_request.ipAddress]["tcp"][port]["name"]
            protocol = results["scan"][scan_request.ipAddress]["tcp"][port]["product"]
            open_ports.append({
                "port": port,
                "protocol": protocol,
                "service": service
            })
    return open_ports
